package com.procurement.inquiry.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.filter.BeanContext;
import com.procurement.inquiry.domain.PcmQuotationProduct;
import com.procurement.inquiry.domain.PcmSupplier;
import com.procurement.inquiry.service.IPcmAuditService;
import com.procurement.inquiry.service.IPcmInquiryDemandService;
import com.procurement.inquiry.service.IPcmInquiryFormService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 我的待办模块
 */
@RestController
@RequestMapping("/mine")
public class PcmAuditController extends  BaseController{
    @Autowired
    private IPcmAuditService pcmAuditService;
    @Autowired
    private IPcmInquiryDemandService pcmInquiryDemandService;
    @Autowired
    private IPcmInquiryFormService pcmInquiryFormService;
    @Autowired(required = false)
    private RemoteFileService remoteFileService;
   // @RequiresPermissions("inquiry:mine:list")

//    公共
    @GetMapping("/list")
    public TableDataInfo list()
    {
        Long userId= SecurityUtils.getUserId();
        List<PcmAudit> list=null; //用来装可以显示数据并版判登陆人
        PcmSupplier pcmSupplier = pcmAuditService.selectPcmSupplier2(userId);
        if (pcmSupplier!=null){
            list=pcmAuditService.selectPcmAuditList(pcmSupplier.getSupplierID2());

        }else {
            list=pcmAuditService.selectPcmAuditList(userId);
        }
        List<PcmAudit> remList = new ArrayList<>();
        //办首页的数据并封装
        for (PcmAudit e : list) {
            //询价
            if (e.getAuditTableYwName().equals("pcm_supplier_quotation")){

                PcmSupplierQuotation pcmSupplierQuotation=pcmAuditService.selectSupplierQuotation((long) Integer.parseInt(e.getAuditTableNumber()));

                pcmSupplier=pcmAuditService.selectPcmSupplier(pcmSupplierQuotation.getQuotingSupplier());

                List<SysFile> sysFiles=pcmAuditService.selectAttach(pcmSupplierQuotation.getQuotationID());
                pcmSupplierQuotation.setSysFile(sysFiles);
                e.setQuoteStatus(pcmSupplierQuotation.getQuoteStatus());
                e.setPcmSupplierQuotation(pcmSupplierQuotation);
                com.ruoyi.system.api.domain.PcmInquiryDemand pcmInquiryDemand=pcmAuditService.selectPcmInquryDemandId(pcmSupplierQuotation.getInquiryDemandNumber());
                e.setPcmInquiryDemand(pcmInquiryDemand);
                List<com.ruoyi.system.api.domain.PcmQuotationProduct> list2=pcmAuditService.selectPcmQuotationProduct(Long.valueOf(e.getAuditTableNumber()));
                list2.forEach(w->{
                    PcmMaterialRecord pcmMaterialRecord=pcmAuditService.selectPcmMaterialRecord(w.getQuotationProductID());
                    w.setPcmMaterialRecord(pcmMaterialRecord);
                    w.setPcmSupplierQuotation(pcmSupplierQuotation);
                });
                String name=SecurityUtils.getUsername();
                e.setSupplierFullName(pcmSupplier.getSupplierFullName());
                e.setUserName(name);
                e.setPcmQuotationProductList(list2);
            }
            else if (e.getAuditTableYwName().equals("pcm_supplier_sample_management")){
                Long auditTableNumber =(long) Integer.parseInt(e.getAuditTableNumber());
                PcmSupplierSampleManagement pcmSupplierSampleManagement=pcmAuditService.selectPcmSupplierSampleManagementBySupplierSampleManagementID(auditTableNumber);
                e.setPcmSupplierSampleManagementList(pcmSupplierSampleManagement);
            }
            else if (e.getAuditTableYwName().equals("srm_approvals")){
                Long auditTableNumber =(long) Integer.parseInt(e.getAuditTableNumber());
                SrmApprovals srmApprovals=pcmAuditService.selectSrmClaAll(auditTableNumber);
                e.setSrmApprovals(srmApprovals);
            }
            else if(e.getAuditTableYwName().equals("pcm_purchase_request")){
                PcmPurchaseRequest pcmPurchaseRequest=pcmAuditService.selectPcmPurchaseRequestByPurchaseRequestNumber(e.getAuditTableNumber());
                System.out.println(pcmPurchaseRequest+"******************"+e.getAuditTableNumber());
                e.setPcmPurchaseRequest(pcmPurchaseRequest);
            }
            else if (e.getAuditTableYwName().equals("pcm_bidding_middle")){
                e.setUserName(SecurityUtils.getUsername());
                e.setAvatar(SecurityUtils.getLoginUser().getSysUser().getAvatar());
                e.setPcmBiddingInviteTenders(pcmAuditService.selInvitationInformation(Long.valueOf(e.getAuditTableNumber())));
            }
            else if (e.getAuditTableYwName().equals("pcm_invited_supplier")){
                e.setUserName(SecurityUtils.getUsername());
                e.setAvatar(SecurityUtils.getLoginUser().getSysUser().getAvatar());
                e.setSupplierFullName(pcmSupplier.getSupplierFullName());
                e.setPcmBiddingInviteTenders(new PcmBiddingInviteTenders());
                e.setPcmInvitedSupplier(pcmAuditService.selByInvitedSupplierId(Long.valueOf(e.getAuditTableNumber())));
                System.out.println(e.getPcmInvitedSupplier()+"**************"+e.getAuditTableNumber());
                if (!e.getPcmInvitedSupplier().getProjectStatus().equals(1)){
                    remList.add(e);
                }
            }
            else if (e.getAuditTableYwName().equals("pcm_expert_supplier")){
                e.setEvaluationContent(pcmAuditService.selEvaluationContent(Long.valueOf(e.getAuditTableNumber())));
                e.getEvaluationContent().put("nickName",SecurityUtils.getLoginUser().getSysUser().getNickName());
            }
        }
        if (remList.size()>0){
            List<Long> remIds = remList.stream().map(PcmAudit::getAuditId).collect(Collectors.toList());
            list = list.stream().filter(item->!remIds.contains(item.getAuditId())).collect(Collectors.toList());
        }
        return getDataTable(list);


        
    }
/*周智*/
    @GetMapping("/selId/{inquiryDemandNumber}/audit/{auditTableNumber}")
    public AjaxResult selectid(@PathVariable("inquiryDemandNumber") String inquiryDemandNumber,@PathVariable("auditTableNumber") String auditTableNumber){
        Long userId= SecurityUtils.getUserId();
        PcmSupplier pcmSupplier=pcmAuditService.selectPcmSupplier2(userId);
        PcmSupplierQuotation pcmSupplierQuotation=pcmAuditService.selectSupplierQuotation2(inquiryDemandNumber,pcmSupplier.getSupplierID2(),auditTableNumber);

        return success(pcmSupplierQuotation);
    }
    @GetMapping(value = "/{inquiryDemandNumber}")
    public AjaxResult inquiryList(@PathVariable("inquiryDemandNumber")String inquiryDemandNumber){
        startPage();
        SysUser user=SecurityUtils.getLoginUser().getSysUser();
        com.procurement.inquiry.domain.PcmInquiryDemand pcmInquiryDemand= pcmInquiryDemandService.selectPcmInquiryDemandByInquiryDemandNumber(inquiryDemandNumber);
        pcmInquiryDemand.getPcmApplicationDetailList().forEach(e->{
            PcmSupplier pcmSupplier=pcmInquiryDemandService.selectSupplier(e.getExpectedSupplier());
            e.setPcmSupplier(pcmSupplier);
        });
        pcmInquiryDemand.setUserlist(user);
        return success(pcmInquiryDemand);
    }
    @PostMapping(value = "upload1")
    public AjaxResult insertQutation(MultipartFile file) throws Exception {
        System.out.println(file);
        SysFile sysFile= remoteFileService.uploadFileMinio(file).getData();
        System.out.println(sysFile);
        System.out.println(1);
        return success(sysFile);
    }
    @PutMapping(value = "quotation")
    public AjaxResult insertQuotation(@RequestBody Map<String,Object> map){
        List<PcmQuotationProduct> list1= (List<PcmQuotationProduct>) map.get("query");
        String s= JSON.toJSONString(list1);
        List<PcmQuotationProduct> pcmQuotationProduct=JSON.parseArray(s,PcmQuotationProduct.class);
        Long la= pcmQuotationProduct.get(0).getPcmSupplierQuotation().getQuotationID();
        List<SysFile> sysFile=pcmQuotationProduct.get(0).getSysFile();
        if (sysFile!=null){
            pcmAuditService.deleteAttach(pcmQuotationProduct.get(0).getPcmSupplierQuotation().getQuotationID());
            sysFile.forEach(e->{
                pcmAuditService.insertAttach(e.getName(),e.getUrl(),pcmQuotationProduct.get(0).getPcmSupplierQuotation().getQuotationID());
            });
        }
        pcmQuotationProduct.forEach(e->{
            System.out.println(e);
            e.getPcmSupplierQuotation().setQuoteStatus(1L);
            int ta=pcmAuditService.updatePcmSupplierQuotation(e.getPcmSupplierQuotation());
            e.setQuotationProductID(e.getPcmMaterialRecord().getProductNumber());
            pcmAuditService.insertPcmQuotationProduct(e);
        });
        LinkedHashMap linkedHashMap= (LinkedHashMap) map.get("as");
        String ss=JSON.toJSONString(linkedHashMap);
        PcmAudit pcmAudit=JSON.parseObject(ss,PcmAudit.class);
//        PcmAudit pcmAudit= (PcmAudit) map.get("as");
        if (pcmAudit.getSupplierid()==1){
            Long supplierId=pcmQuotationProduct.get(0).getPcmSupplierQuotation().getQuotingSupplier();
            Long AuditId=pcmAudit.getAuditId();
            pcmAuditService.updateAudit(AuditId,supplierId);
        }else {
            Long supplierId= 1L;
            Long AuditId=pcmAudit.getAuditId();
            pcmAuditService.updateAudit(AuditId,supplierId);
        }
        return toAjax(1);
    }
    @GetMapping(value = "/pro/{productNumber}")
    public AjaxResult selectPcmM(@PathVariable("productNumber")String productNumber){
        PcmMaterialRecord pcmMaterialRecord=pcmAuditService.selectPcmMaterialRecord(productNumber);
        return success(pcmMaterialRecord);
    }
    @PostMapping(value = "updatepro")
    public AjaxResult updateQ(@RequestBody Map<String,Object> map){
//        List<PcmQuotationProduct> list
        List<PcmQuotationProduct> list1= (List<PcmQuotationProduct>) map.get("date");
        String s= JSON.toJSONString(list1);
        List<PcmQuotationProduct> list=JSON.parseArray(s,PcmQuotationProduct.class);
        int ta=pcmAuditService.updatePcmSupplierQuotation(list.get(0).getPcmSupplierQuotation());
        System.out.println(list.get(0).getPcmSupplierQuotation());
        List<SysFile> sysFile=list.get(0).getSysFile();
        if (sysFile!=null){
            pcmAuditService.deleteAttach(list.get(0).getPcmSupplierQuotation().getQuotationID());
            sysFile.forEach(e->{
                pcmAuditService.insertAttach(e.getName(),e.getUrl(),list.get(0).getPcmSupplierQuotation().getQuotationID());
            });
        }
        System.out.println(new JSONArray(sysFile));
        list.forEach(e->{
            e.setQuotationProductID(e.getPcmMaterialRecord().getProductNumber());
            pcmAuditService.updatePcmQuotationProduct(e);
        });
        LinkedHashMap linkedHashMap= (LinkedHashMap) map.get("as");
        String ss=JSON.toJSONString(linkedHashMap);
        PcmAudit pcmAudit=JSON.parseObject(ss,PcmAudit.class);
//        PcmAudit pcmAudit= (PcmAudit) map.get("as");
        if (pcmAudit.getSupplierid()==1L){
            Long supplierId=list.get(0).getPcmSupplierQuotation().getQuotingSupplier();
            Long AuditId=pcmAudit.getAuditId();
            pcmAuditService.updateAudit(AuditId,supplierId);
        }else {
            Long supplierId= 1L;
            Long AuditId=pcmAudit.getAuditId();
            pcmAuditService.updateAudit(AuditId,supplierId);
        }

        return toAjax(1);
    }
    @GetMapping("/selQuo/{quotationID1}")
    public TableDataInfo selectQuo(@PathVariable("quotationID1")String quotationID1){
        System.out.println(quotationID1);
        List<com.ruoyi.system.api.domain.PcmQuotationProduct> list=pcmAuditService.selectPcmQuotationProduct(Long.valueOf(quotationID1));
        PcmSupplierQuotation pcmSupplierQuotation=pcmAuditService.selectSupplierQuotation(Long.valueOf(quotationID1));
        list.forEach(e->{
            PcmMaterialRecord pcmMaterialRecord=pcmAuditService.selectPcmMaterialRecord(e.getQuotationProductID());
            e.setPcmMaterialRecord(pcmMaterialRecord);
            e.setPcmSupplierQuotation(pcmSupplierQuotation);
        });
        return getDataTable(list);
    }
    @PutMapping("/updAudit")
    public AjaxResult updateAudit(@RequestBody PcmAudit pcmAudit){
        pcmAuditService.updatePcmAudit(pcmAudit.getCirculationStatus(),pcmAudit.getAuditId());

        return toAjax(1);
    }
/*文志海*/




    /*李扬*/
    @RequestMapping("/updateAuditRequest")
    public AjaxResult updatePcmPurchaseRequest(@RequestBody PcmAudit pcmAudit){
        return toAjax(pcmAuditService.updatePcmPurchaseRequest(pcmAudit));
    }

    @RequestMapping("/updateRequest")
    public AjaxResult updateRequest(@RequestBody PcmPurchaseRequest purchaseRequest){
        if(purchaseRequest.getPurchaseStatus()==1){
            pcmAuditService.updateApplicationDetail(purchaseRequest.getPurchaseRequestNumber());
        }
        return toAjax(pcmAuditService.updateRequest(purchaseRequest));
    }






    /*冯星瑞*/



}